//
//  HMEmotionView.swift
//  01-表情
//
//  Created by mac on 15/10/25.
//  Copyright © 2015年 itheima. All rights reserved.
//

import UIKit

let collectionViewCellId = "collectionViewCellId"
class HMEmotionView: UIView {
    // 选中表情回调
    private var selectedEmotionCallback: (emoticon:HMEmoticon) -> ()
    // 监听toolBar的点击
    @objc private func itemClick(item: UIBarButtonItem) {
        print(item.tag)
        let indexPath = NSIndexPath(forItem: 0, inSection: item.tag)
        collectionView.scrollToItemAtIndexPath(indexPath, atScrollPosition: .Left, animated: true)
    }
    // MARK: -构造函数
    init(selectedEmoticon:(emoticon:HMEmoticon) -> ()) {
        self.selectedEmotionCallback = selectedEmoticon
        var rect = UIScreen.mainScreen().bounds
        // rect.height是只读属性，不能赋值
        rect.size.height = 226
        super.init(frame: rect)
        setupUI()
        // 滚到 “ 默认”
        let indexPath = NSIndexPath(forItem: 0, inSection: 1)
        // 还获得不到数据
        dispatch_async(dispatch_get_main_queue()) { () -> Void in
            self.collectionView.scrollToItemAtIndexPath(indexPath, atScrollPosition: .Left, animated: false)
        }
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    private lazy var packages = HMEmoticonManager.sharedManager.packages
    // 设置layout
    class EmotionLayout: UICollectionViewFlowLayout {
        override func prepareLayout() {
            super.prepareLayout()
            let col: CGFloat = 7
            let row: CGFloat = 3
            let w = collectionView!.bounds.width/col
            let margin = (collectionView!.bounds.height - w * row) * 0.449
            itemSize = CGSize(width: w, height: w)
            minimumInteritemSpacing = 0
            minimumLineSpacing = 0
            sectionInset = UIEdgeInsetsMake(margin, 0, margin, 0)
            scrollDirection = .Horizontal
            collectionView?.pagingEnabled = true
            
            collectionView?.showsHorizontalScrollIndicator = false
            collectionView?.bounces = false
        }
    }
    /// 懒加载控件
    private lazy var collectionView:UICollectionView = UICollectionView(frame: CGRectZero, collectionViewLayout: EmotionLayout())
    private lazy var toolBar: UIToolbar = UIToolbar()

}
// MARK: - 设置界面
private extension HMEmotionView{
    /// 设置界面
    func setupUI() {
        // 添加控件
        addSubview(toolBar)
        addSubview(collectionView)
        // 自动布局
        toolBar.snp_makeConstraints { (make) -> Void in
            make.bottom.equalTo(self.snp_bottom)
            make.left.equalTo(self.snp_left)
            make.right.equalTo(self.snp_right)
            make.height.equalTo(44)
        }
        collectionView.snp_makeConstraints { (make) -> Void in
            make.top.equalTo(self.snp_top)
            make.bottom.equalTo(toolBar.snp_top)
            make.left.equalTo(self.snp_left)
            make.right.equalTo(self.snp_right)
        }
        
        // 准备控件
        prepareToolbar()
        prepareCollectionView()
    }
    /// 准备工具栏
    func prepareToolbar() {
        // 渲染颜色
        toolBar.tintColor = UIColor.darkGrayColor()
        // 设置按钮的内容
        var items = [UIBarButtonItem]()
        // 区分item
        var index = 0
         //let array = ["最近","默认","emoji","浪小花"]
        for d in packages {
            items.append(UIBarButtonItem(title: d.group_name_cn, style: .Plain, target: self, action: "itemClick:"))
            items.last?.tag = index++
            // 添加弹簧
            items.append(UIBarButtonItem(barButtonSystemItem: .FlexibleSpace, target: nil, action: nil))
        }
        // 移除最后一个（弹簧）
        items.removeLast()
        // 设置item
        toolBar.items = items
    }
     /// 准备工具栏
    func prepareCollectionView(){
        // 注册可重用cell
        collectionView.registerClass(HMCollectionViewCell.self, forCellWithReuseIdentifier: collectionViewCellId)
        
        collectionView.backgroundColor = UIColor.lightGrayColor()
        // 设置数据源
        collectionView.dataSource = self
        collectionView.delegate = self
    }
}
// MARK: - 数据源，代理
extension HMEmotionView: UICollectionViewDataSource,UICollectionViewDelegate{
    func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
        print("点击cell")
        let em = packages[indexPath.section].emoticons[indexPath.item]
        selectedEmotionCallback(emoticon: em)
    }
    func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
        return packages.count
    }
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return packages[section].emoticons.count
    }
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(collectionViewCellId, forIndexPath: indexPath) as! HMCollectionViewCell
        
        cell.emoticon = packages[indexPath.section].emoticons[indexPath.item]
        return cell
    }
}
// MARK: - 自定义cell
class HMCollectionViewCell: UICollectionViewCell {
    var emoticon: HMEmoticon? {
        didSet{
            emotionBtn.setImage(UIImage(contentsOfFile: emoticon!.imagePath), forState:UIControlState.Normal)
            emotionBtn.setTitle(emoticon?.emoji, forState: UIControlState.Normal)
            if emoticon!.isRemoved {
                emotionBtn.setImage(UIImage(named: "compose_emotion_delete"), forState: UIControlState.Normal)
            }
        }
    }
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    /// 懒加载控件
    private lazy var emotionBtn: UIButton = UIButton()
    // MARK: - 设置UI
    private func setupUI(){
        // 添加
        contentView.addSubview(emotionBtn)
        emotionBtn.backgroundColor = UIColor.yellowColor()
        // 布局
        emotionBtn.frame = CGRectInset(bounds, 4, 4)
        // emoji的图片太小，原因：emoji本身就是文本
        // 要设置文本大小和图片稿度一样
        emotionBtn.titleLabel?.font = UIFont.systemFontOfSize(32)
        
        // 不能交互
        emotionBtn.userInteractionEnabled = false
    }
}